package cc.laop.mq.redis.consumer;

import cc.laop.mq.redis.RedisConstants;
import cc.laop.mq.utils.ApplicationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * Created by Pengpeng on 2017/5/26.
 */
@Component
public class RedisConsumer {

    private static final Logger logger = LoggerFactory.getLogger(RedisConsumer.class);

    @Autowired
    private RedisTemplate<Serializable, Object> redisTemplate;

    public void recieve() {
        Object message = redisTemplate.opsForList().rightPop(RedisConstants.REDIS_LIST_KEY);
        if (message != null) {
            logger.info("Redis recieve message: {}", message);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            logger.info("Redis consumer starting...");
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
                    ("classpath:spring/spring-redis.xml");
            context.start();
            logger.info("Redis consumer started.");
        }).start();

        Thread.sleep(10000);
        RedisConsumer redisConsumer = (RedisConsumer) ApplicationUtils.getBean(RedisConsumer.class);
        while (true) {
            redisConsumer.recieve();
            Thread.sleep(2000);
        }
    }

}
